const fs = require('fs');
const path = require('path');

// 加载 JSON 映射表
const docMap = require('./docMap.json');

// 用于记录一级目录信息
const groups = {};
let groupOrderCounter = 0;

// 收集所有的一级目录并生成 group 信息
Object.entries(docMap).forEach(([filePath, title]) => {
  if (!filePath.endsWith('.md')) return; // 忽略目录项本身

  const parts = filePath.split('/');
  const firstLevelDir = parts[1]; // 如 low-code-guide

  if (!groups[firstLevelDir]) {
    const dirKey = `docs/${firstLevelDir}/`;
    const chineseTitle = typeof docMap[dirKey] === 'string' ? docMap[dirKey] : firstLevelDir;

    groups[firstLevelDir] = {
      title: chineseTitle,
      path: `/${firstLevelDir}`,
      order: groupOrderCounter++,
    };
  }
});

// 构建 nav 和 sidebar 结构
const nav = [];
const sidebar = {};

// 记录每个 group 的子页面
const groupPages = {};

Object.entries(docMap).forEach(([filePath, title]) => {
  if (!filePath.endsWith('.md')) return;

  const parts = filePath.split('/');
  const firstLevelDir = parts[1];

  const fileName = parts[parts.length - 1].replace(/\.md$/, '');

  // 构造链接路径
  const linkPath = filePath.replace(/^docs\//, '').replace(/\.md$/, '');

  // 获取 group 信息
  const group = groups[firstLevelDir];

  // 添加到 nav（只添加一级目录）
  if (group && !nav.find(n => n.link === group.path)) {
    nav.push({
      title: group.title,
      link: group.path,
    });
  }

  // 构建 sidebar[group.path]
  if (!sidebar[group.path]) {
    sidebar[group.path] = [];
    groupPages[group.path] = [];
  }

  // 排除 index.md 和 README.md 的标题
  const displayTitle = fileName === 'index' || fileName === 'README' ? group.title : title;

  // 添加条目
  groupPages[group.path].push({
    title: displayTitle,
    link: `/${linkPath}`,
  });
});

// 根据 group.order 对 nav 排序
nav.sort((a, b) => {
  const keyA = a.link.replace(/^\//, '');
  const keyB = b.link.replace(/^\//, '');
  return (groups[keyA]?.order || 0) - (groups[keyB]?.order || 0);
});

// 根据文件顺序对 sidebar 分组排序
Object.keys(groupPages).forEach(groupPath => {
  const pages = groupPages[groupPath];
  pages.sort((a, b) => a.link.localeCompare(b.link)); // 按字母排序
  sidebar[groupPath] = pages;
});

// 写入 nav.js
const navContent = `// nav.js\nmodule.exports = ${JSON.stringify(nav, null, 2)};`;
fs.writeFileSync(path.join(__dirname, 'nav.js'), navContent, 'utf-8');
console.log('✅ 已生成：nav.js');

// 写入 sidebar.js
const sidebarContent = `// sidebar.js\nmodule.exports = ${JSON.stringify(sidebar, null, 2)};`;
fs.writeFileSync(path.join(__dirname, 'sidebar.js'), sidebarContent, 'utf-8');
console.log('✅ 已生成：sidebar.js');